package com.foo.common.base.utils.laboratory.xml;

import java.beans.IntrospectionException;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;

import com.foo.common.base.pojo.MavenDependencyModel;
import com.foo.common.base.utils.FooUtils;
import com.foo.common.base.utils.laboratory.httpClient.MavenSearchResultJson;
import com.foo.common.base.utils.laboratory.jaxb.autoGenerated.Dependency;
import com.foo.common.base.utils.laboratory.jaxb.autoGenerated.Model;
import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class PomHelper {

	private final static Logger logger = LoggerFactory
			.getLogger(PomHelper.class);

	public static void main5(String[] args) {
		logger.info("result:{}", "${mail.version}".startsWith("$"));
		logger.info("result:{}", "${mail.version}".replaceAll("\\$", "")
				.replaceAll("\\{", "").replaceAll("\\}", ""));
	}

	public static String getPomDependencyNewestVersion(String groupId,
			String artifactId) throws Exception {

		groupId = groupId.trim();
		artifactId = artifactId.trim();

		logger.trace("groupId:【{}】 and artifactId:【{}】 analyze start.",
				groupId, artifactId);

		Stopwatch stopwatch = Stopwatch.createStarted();

		CloseableHttpClient httpclient = HttpClients.createDefault();

		String url = "http://search.maven.org/solrsearch/select?q=g:%22"
				+ groupId + "%22+AND+a:%22" + artifactId + "%22&rows=1&wt=json";

		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		HttpGet httpGet = new HttpGet(url);
		String responseBody = httpclient.execute(httpGet, responseHandler);
		// responseBody = new String(responseBody.getBytes("ISO-8859-1"),
		// "UTF-8");

		Gson gson = new GsonBuilder().serializeNulls().create();
		MavenSearchResultJson object = new MavenSearchResultJson();
		object = gson.fromJson(responseBody, MavenSearchResultJson.class);

		stopwatch.stop();
		logger.trace(
				"groupId:【{}】 and artifactId:【{}】 analyze end.Newest version:【{}】",
				groupId, artifactId, object.getVersion());
		logger.trace("all cost time:{}", stopwatch);
		return object.getVersion();
	}

	@SuppressWarnings("unchecked")
	public static Set<MavenDependencyModel> getPomDependencySet(File file)
			throws Exception {
		// File file = FooUtils.getTestMavenPomFile();
		JAXBContext jaxbContext = JAXBContext
				.newInstance("com.foo.common.base.utils.laboratory.jaxb.autoGenerated");
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		JAXBElement<Model> jaxbElement = (JAXBElement<Model>) jaxbUnmarshaller
				.unmarshal(file);
		Model model = (Model) jaxbElement.getValue();

		Map<String, String> versionMap = Maps.newHashMap();
		for (Element myProperty : model.getProperties().getAny()) {
			versionMap.put(myProperty.getLocalName(),
					myProperty.getTextContent());
		}

		logger.debug("versionMap is:{}", versionMap);

		String versionNumber = "";
		String tmpVersion = "";
		MavenDependencyModel mavenDependencyModel = null;
		Set<MavenDependencyModel> mySet = Sets.newTreeSet();
		for (Dependency dependency : model.getDependencies().getDependency()) {
			mavenDependencyModel = new MavenDependencyModel();
			tmpVersion = dependency.getVersion();
			if (tmpVersion.startsWith("$")) {
				versionNumber = versionMap.get(tmpVersion.replaceAll("\\$", "")
						.replaceAll("\\{", "").replaceAll("\\}", ""));
			} else {
				versionNumber = tmpVersion;
			}
			mavenDependencyModel.setGroupId(dependency.getGroupId());
			mavenDependencyModel.setArtifactId(dependency.getArtifactId());
			mavenDependencyModel.setVersion(versionNumber);
			mavenDependencyModel.setType(Strings.nullToEmpty(dependency
					.getType()));
			mySet.add(mavenDependencyModel);
			logger.info("adding dependency of:{}", mavenDependencyModel);
		}
		return mySet;
	}

	@SuppressWarnings("unchecked")
	public static void main3(String[] args) throws JAXBException,
			IllegalArgumentException, IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		File file = FooUtils.getTestMavenPomFile();
		JAXBContext jaxbContext = JAXBContext
				.newInstance("com.foo.common.base.utils.laboratory.jaxb.autoGenerated");
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		JAXBElement<Model> jaxbElement = (JAXBElement<Model>) jaxbUnmarshaller
				.unmarshal(file);
		Model model = (Model) jaxbElement.getValue();

		for (Element myProperty : model.getProperties().getAny()) {
			// logger.info("properties:{}", FooUtils.reflectToString(string));
			if (myProperty.getLocalName().equals("struts.version")) {
				// System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
				myProperty.setTextContent("1231313");
				myProperty.removeAttribute("xmlns:xsi");
				myProperty.removeAttribute("xmlns");
			}
		}

		for (Dependency dependency : model.getDependencies().getDependency()) {
			System.out.println(dependency.getVersion());

		}

		Marshaller m = jaxbContext.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		// 删除xmlns:xsi
		m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,
				"properties");

		m.marshal(jaxbElement, System.out);

		logger.info("generated end.");

	}

	public static void main1(String[] args) throws JAXBException {

		// JaxbPomModel model = new JaxbPomModel();
		// model.setProperties("fuck......");
		//
		// // File file = new File("C:\\file.xml");
		// JAXBContext jaxbContext = JAXBContext.newInstance(Model.class);
		// Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
		//
		// // output pretty printed
		// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		//
		// // jaxbMarshaller.marshal(model, file);
		// jaxbMarshaller.marshal(model, System.out);

	}
}
